<template>
  <van-field
    v-model="value"
    :name="params.value"
    :label="params.label"
    :readonly="params.readonly"
    :placeholder="params.placeholder"
    v-bind="{ ...params.bind }"
    @blur="getInputData"
    @change="changeData"
  >
    <template v-if="params.rightSlot" #right-icon>
      <component :is="params.rightSlot" />
    </template>
  </van-field>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import regexFunctions from '@/utils/regex.js'

// 校验并返回第一个错误
const validateByRegex = (input, regex) => {
  let flag = ''
  for (const element of regex) {
    if (!regexFunctions[element.regFun](input)) {
      flag = element.msg
      break
    }
  }
  return flag
}

const props = defineProps(['params', 'modelValue', 'formParams'])

const value = ref(props.modelValue)

const emits = defineEmits(['update:modelValue', 'validate', 'getText'])

const changeData = () => {
  if (
    value.value &&
    props.params.event &&
    props.params.event.type === 'change'
  ) {
    props.params.event.funcName()
  }
}

const getInputData = () => {
  if (value.value && props.params.event && props.params.event.type === 'blur') {
    props.params.event.funcName()
  }

  // blur触发时 向父组件返回值 并将数据校验暴露出来
  emits('update:modelValue', value.value)
  if (props.params.regex) {
    // 校验数据是否符合规则
    const res = validateByRegex(value.value, props.params.regex)
    emits('validate', {
      name: props.params.value,
      validateRes: res === '',
      validateMsg: res,
    })
  }
}

onMounted(() => {
  getInputData()
})

watch(
  () => props.modelValue,
  newVal => {
    value.value = newVal
  },
)
</script>
